package com.lagou.ipersistence.binding;

import com.lagou.ipersistence.session.SqlSession;

import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author Yan Jiahong
 * Created on 2020/11/22
 */
public class MapperProxyFactory<T> {
    private final Class<T> mapperInterface;
    private final Map<Method, MapperMethod> methodCache = new ConcurrentHashMap<>();
    
    public MapperProxyFactory(Class<T> mapperInterface) {
        this.mapperInterface = mapperInterface;
    }
    
    protected T newInstance(MapperProxy<T> mapperProxy) {
        return (T) Proxy.newProxyInstance(mapperInterface.getClassLoader(), new Class[]{ mapperInterface}, mapperProxy);
    }
    
    public T newInstance(SqlSession session) {
        final MapperProxy<T> mapperProxy = new MapperProxy<>(session, mapperInterface, methodCache);
        return newInstance(mapperProxy);
    }
}
